﻿using System.Collections;
using System.Collections.Generic;

public abstract class FSMState 
{
    public abstract int stateId { get; }

    //public abstract string name{ get; }

    protected FSMController m_Controller;
    public FSMController controller => m_Controller;

    protected List<FSMTransition> m_Transitions;
    public List<FSMTransition> transitions => m_Transitions;

    public FSMState()
    {

    }
    
    public FSMState(FSMController controller) 
    {
        m_Controller = controller;
        controller.AddState(this);
    }

    public void AddTransition(FSMTransition transition)
    {
        var toState = transition.toState;
        if (toState == null)
        {
            GameDebug.LogError("toState == null");
            return;
        }
        if (m_Transitions == null)
            m_Transitions = new List<FSMTransition>();
        
        m_Transitions.Add(transition);
        
        /*var exist = m_Transitions.Find(t => t.toState == toState);

        if (exist == null)
        {
            m_Transitions.Add(transition);
        }
        else
        {
            GameDebug.LogError($"{this.GetType().Name} 到 {toState.GetType().Name} 的过渡已存在");
        }*/
        transition.fromState = this;
    }

    public FSMTransition CheckTransition()
    {
        if (m_Transitions != null)
        {
            foreach (var transit in m_Transitions)
            {
                if (transit.Meet())
                {
                    return transit;
                }
            }
        }

        return null;
    }
    public FSMTransition CheckSign(int sign)
    {
        if (m_Transitions != null)
        {
            foreach (var transit in m_Transitions)
            {
                if (transit.MeetSign(sign))
                {
                    return transit;
                }
            }
        }
        return null;
    }

    public virtual void OnEnter(FSMState preState)
    {

    }

    public virtual void Update(float deltaTime)
    {

    }

    public virtual void OnExit(FSMState nextState)
    {

    }
    
}
